import { Module } from 'vuex'
import { IRootState } from '../type'
import router from '@/router'
import {
  accountLoginRequest,
  RequestUserInfoById,
  requestUserMenusByRoleId,
} from '@/service/login/login'
import localCache from '@/utils/cache'
import { mapMenusToRouters } from '@/utils/map-menus'

interface IloginState {
  token: string
  userInfo: any
  userMenus: any
}
const loginModule: Module<IloginState, IRootState> = {
  namespaced: true, //命名空间
  state: () => {
    return {
      token: '',
      userInfo: {},
      userMenus: [],
    }
  },
  mutations: {
    changeToken(state, token: string) {
      state.token = token
    },
    changeUserInfo(state, userInfo: any) {
      state.userInfo = userInfo
    },
    changeUserMenus(state, userMenus: any) {
      state.userMenus = userMenus
      const routes = mapMenusToRouters(userMenus)
      routes.forEach((item) => {
        router.addRoute('main', item)
      })
      // console.log(routes)
    },
  },
  getters: {},
  actions: {
    async accountLoginAction({ commit }, payload: any) {
      // 1.实现登录逻辑
      const loginReslut = await accountLoginRequest(payload)
      const { token, id } = loginReslut.data
      commit('changeToken', token)
      localCache.setCache('token', token)

      // 2.拿到用户信息
      const userInfoResult = await RequestUserInfoById(id)
      const userInfo = userInfoResult.data
      commit('changeUserInfo', userInfo)
      localCache.setCache('userInfo', userInfo)

      // 3.请求用户菜单
      const userMenusResult = await requestUserMenusByRoleId(userInfo.role.id)
      const userMenus = userMenusResult.data
      commit('changeUserMenus', userMenus)
      localCache.setCache('userMenus', userMenus)
      console.log(userMenus)
      // 4.跳转到首页
      router.push('/main')
    },
    // 5.获取本地缓存中的数据到vuex
    loadLocalLogin({ commit }) {
      const token = localCache.getCache('token')
      if (token) {
        commit('changeToken', token)
      }
      const userInfo = localCache.getCache('userInfo')
      if (userInfo) {
        commit('changeUserInfo', userInfo)
      }
      const userMenus = localCache.getCache('userMenus')
      if (userMenus) {
        commit('changeUserMenus', userMenus)
      }
    },
  },
}
export default loginModule
